<!-- 系统设置 -->
<script setup lang="ts" >
import { nextTick, ref, toRaw } from 'vue'
import { ElInput } from 'element-plus'
import Editor from './components/Editor.vue'
import breadCrumb from '@/components/breadCrumb.vue'
import { useUserStore } from '@/store/userinfo.js'
import { setDepartment, getDepartment, setProduct, getProduct } from '@/api/set.js'
import { bus } from '@/utils/mitt.js'
// import date from './components/date.vue'
//头像绑定账号
import { bindAtarAndAccount, putName, putEmail, putSex } from '@/api/userinfo.js'
import ChangePassword from './components/ChangePassword.vue'
const userStore = useUserStore()
//面包屑
const item = ref({
  first: '系统设置',
})
//显示哪个图标
const iconName = ref({
  name: 'set'
})
//默认打开栏目
const activeName = ref('first')
//上传图像-------------------------------------------------------
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

import type { UploadProps } from 'element-plus'
//展示文件列表的
const imageUrl = ref('')
//文件上传成功钩子 -头像
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  //展示文件列表信息的
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  // console.log(response);    action后端返回的参数
  // console.log(uploadFile);  上传文件的信息
  if (response.status == 0) {
    //更改store里的图片地址  pinia里$patch修改
    userStore.$patch({
      imageUrl: response.url
    }),
      (async () => {
        const res = await bindAtarAndAccount(userStore.account, response.onlyId, response.url)
        console.log(res);
      })()

    ElMessage.success('上传头像成功')
  } else {
    ElMessage.success('上传头像失败')
  }
}
//上传失败的钩子
const handleAvatarError = () => {
  ElMessage.error('上传头像失败')
}//上传文件之前的钩子，参数为上传的文件， 若返回false或者返回 Promise 且被 reject，则停止上传
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('头像必须是jpeg格式')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('头像大小要小于 2MB!')
    return false
  }
  return true
}
//用户信息 直接保存到store里了-------------------------------------------------------
// const accountInfo = reactive({
//   account: '',
//   indentity: '',
//   department: '',
//   name: '',
//   sex: '',
//   email: ''
// })
const changePass = ref()
const openchangePass = () => {
  changePass.value.openDiaLog()
  console.log(changePass.value);
}
// 修改接口
const changeName = async () => {
  const res = await putName(localStorage.getItem('id'), userStore.name)
  // console.log(res);
  if (res.status == 0) {
    ElMessage.success('修改成功')
  } else {
    ElMessage.error('修改失败!匹配由2-10个汉字组成的字符串,并且可以重复"·"和2-10个汉字的组合0-2次')
  }
}
const changeSex = async () => {
  const res = await putSex(localStorage.getItem('id'), userStore.sex)
  // console.log(res);
  if (res.status == 0) {
    ElMessage.success('修改成功')
  } else {
    ElMessage({
      type: 'error',
      message: 'cccc'
    })
  }
}
const changeEmail = async () => {
  const res = await putEmail(localStorage.getItem('id'), userStore.email)
  // console.log(res);
  if (res.status == 0) {
    ElMessage.success('修改成功')
  } else {
    ElMessage({
      type: 'error',
      message: 'cccc'
    })
  }
}
//上传时附带的额外参数 从 v2.3.13 支持
// const testData = ref('swiper1')
//公司信息 公司名称--------------------------------------------
import { getCompanyName, changeCompanyName, getAllSwiper } from '@/api/set.js'
const companyName = ref()
const getCompanyname = async () => {
  companyName.value = await getCompanyName()
}
getCompanyname()
//
const changeCompanyname = async () => {
  const res = await changeCompanyName(companyName.value)
  console.log(res);
  if (res.status == 0) {
    ElMessage.success('修改成功')
  } else {
    ElMessage.success('修改失败')
  }
}
// 打开富文本，参数1，2，3，4,打开对应文本
const editor = ref()
const openEditor = (id: number) => {
  editor.value.open()
  bus.emit('editorTitle', id)
  // console.log(id);
}
//- 上传轮播图成功，系统设置-首页管理------------------------------
const handleSwiperSuccess: UploadProps['onSuccess'] = (response,
  uploadFile) => {
  console.log(response);
  getAllswiper()
}
const imageSwiper = ref()
const swiperData = [
  { name: 'swiper1' },
  { name: 'swiper2' },
  { name: 'swiper3' },
  { name: 'swiper4' },
  { name: 'swiper5' },
  { name: 'swiper6' },]
const getAllswiper = async () => {
  const res = await getAllSwiper()
  // console.log(res);
  imageSwiper.value = res
}
getAllswiper()

// 部门设置-------------------------------
const inputValue = ref('')
const dynamicTags = ref([])
const inputVisible = ref(false)
const InputRef = ref<InstanceType<typeof ElInput>>()
//关闭时的函数---------
const handleClose = async (tag: string) => {
  dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1)
  //传入后端原生数据
 await setDepartment(JSON.stringify(toRaw(dynamicTags.value)))
  // console.log(res);  //打印数据d的变化 toRaw把响应式数据变为原生数据
}
//-----------------------------------设置动态标签
const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}
// 输入时的函数---------
const handleInputConfirm = async () => {
  if (inputValue.value) {
    dynamicTags.value.push(inputValue.value)
    const res = await setDepartment(JSON.stringify(toRaw(dynamicTags.value)))
    // console.log(res);
  }
  inputVisible.value = false
  inputValue.value = ''
}
//动态部门
const getdepartment = async () => {
  const res = await getDepartment()
  dynamicTags.value=res
}
getdepartment()
</script>

<template>
  <!-- 面包屑组件 -->
  <breadCrumb :item="item" :iconName="iconName" />
  <!-- 系统设置页修改密码 -->
  <ChangePassword ref="changePass" />
  <!-- 富文本  -->
  <Editor ref="editor" />
  <!-- 栏目切换 -->
  <div class="common-warpped">
    <div class="common-content">
      <el-tabs v-model="activeName" class="demo-tabs">
        <!-- 账号信息 ---------------------------------------------------- -->
        <el-tab-pane label="账号信息" name="first">
          <!-- 用户头像 -->
          <div class="account_info_wapper">
            <span>用户头像</span>
            <div class="account_info_content">
              <!-- action是上传图像的接口
                  data上传时附带的参数 {}，，会分割成对象数据，后端要拼接成完整的
              -->
              <el-upload class="avatar-uploader" action="http://127.0.0.1:3007/user/uploadAvatar" :show-file-list="false"
                list-type="picture" :on-success="handleAvatarSuccess" :on-error="handleAvatarError"
                :before-upload="beforeAvatarUpload" :drag="true">
                <img v-if="userStore.imageUrl" :src="userStore.imageUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon">
                  <i style="font-size: 12px;">请上传/支持拖拽</i>
                  <Plus />
                </el-icon>
              </el-upload>
            </div>
          </div>
          <!-- 用户账号 -->
          <div class="account_info_wapper">
            <span>用户账号:</span>
            <div class="account_info_content">
              <el-input v-model="userStore.account" disabled></el-input>
            </div>
          </div>
          <!-- 用户密码 -->
          <div class="account_info_wapper">
            <span>用户密码:</span>
            <div class="account_info_content">
              <el-button type="primary" @click="openchangePass">修改密码</el-button>
            </div>
          </div>
          <!-- 用户姓名 -->
          <div class="account_info_wapper">
            <span>用户姓名:</span>
            <div class="account_info_content">
              <el-input v-model="userStore.name"></el-input>
            </div>
            <el-button type="primary" @click="changeName">保存</el-button>
          </div>
          <!-- 用户性别 -->
          <div class="account_info_wapper">
            <span>用户性别:</span>
            <div class="account_info_content">
              <el-select v-model="userStore.sex">
                <el-option label="男生" value="男生" />
                <el-option label="女生" value="女生" />
              </el-select>
            </div>
            <el-button type="primary" @click="changeSex">保存</el-button>
          </div>
          <!-- 用户身份 -->
          <div class="account_info_wapper">
            <span>用户身份:</span>
            <div class="account_info_content">
              <el-input v-model="userStore.indentity" disabled></el-input>
            </div>
          </div>
          <!-- 用户部门 -->
          <div class="account_info_wapper">
            <span>用户部门:</span>
            <div class="account_info_content">
              <el-input v-model="userStore.department" disabled></el-input>
            </div>
          </div>
          <!-- 用户邮箱 -->
          <div class="account_info_wapper">
            <span>用户邮箱:</span>
            <div class="account_info_content">
              <el-input v-model="userStore.email"></el-input>
            </div>
            <el-button type="primary" @click="changeEmail">保存</el-button>
          </div>
          <!-- <date/> -->
        </el-tab-pane>
        <!-- 公司信息 ---------------------------------------------------- -->
        <el-tab-pane label="公司信息" name="second">
          <div class="account_info_wapper">
            <span>公司名称:</span>
            <div class="account_info_content">
              <el-input v-model="companyName"></el-input>
            </div>
            <el-button type="primary" @click="changeCompanyname">编辑公司名称</el-button>
          </div>
          <div class="account_info_wapper">
            <span>公司介绍:</span>
            <div class="account_info_content">
              <el-button type="primary" @click="openEditor(1)">编辑公司介绍</el-button>
            </div>
          </div>
          <div class="account_info_wapper">
            <span>公司架构:</span>
            <div class="account_info_content">
              <el-button type="primary" @click="openEditor(2)">编辑公司架构</el-button>
            </div>
          </div>
          <div class="account_info_wapper">
            <span>公司战略:</span>
            <div class="account_info_content">
              <el-button type="primary" @click="openEditor(3)">编辑公司战略</el-button>
            </div>
          </div>
          <div class="account_info_wapper">
            <span>公司人员:</span>
            <div class="account_info_content">
              <el-button type="primary" @click="openEditor(4)">编辑公司人员</el-button>
            </div>
          </div>

        </el-tab-pane>
        <!-- 首页管理 -->
        <el-tab-pane label="首页管理" name="third" class="home_wapped">
          <div class="siwperWarpped" v-for="(item, index) of swiperData" :key="index">
            <div class="swiper1">
              <span>轮播图{{ index + 1 }}</span>
              <el-upload action="http://127.0.0.1:3007/set/uploadSwiper" :show-file-list="false"
                :on-success="handleSwiperSuccess" :data="item">
                <template #trigger>
                  <img v-if="imageSwiper" :src="imageSwiper[index]" class="imgSize" />
                  <img src="@/assets/马赛克.png" alt="没上传图片~~" v-else>
                </template>
              </el-upload>
            </div>
          </div>
        </el-tab-pane>
        <!--其他设置  -->
        <el-tab-pane label="其他设置" name="fourth">
          <div class="set">
            <div class="departmentSet">
              <span>部门设置:</span>
              <el-tag v-for="tag in dynamicTags" :key="tag" class="mx-1"
               closable :disable-transitions="false" :hit="true"
               size="large"
                round
                @close="handleClose(tag)">
                {{ tag }}
              </el-tag>
              <el-input v-if="inputVisible" ref="InputRef" v-model="inputValue" class="ml-2 w-30" size="small"
                @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" />
              <el-button v-else class="button-new-tag ml-1" size="small" @click="showInput">
                + 新建标签
              </el-button>
            </div>
            <div class="productSet">
              <span>产品设置:</span>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
  <!--  -->
</template>

<style scoped lang="scss">
// 外壳
.common-warpped {
  background: linear-gradient(45deg, #8E7E9E 25%, #2980b9 75%);
  height: calc(100vh - 85px);
  padding: 8px;


  //内容
  .common-content {
    padding: 0 12px;
    height: 100%;
    background-color: #fff;

    // 账号信息
    .account_info_wapper {
      display: flex;
      align-items: center;
      margin-top: 18px; //间隔
      margin-left: 5%;

      .el-input {
        margin-right: 20px;
      }

      .el-button {
        margin-left: 20px;

      }

      span {
        margin-right: 30px;
      }

      .account_info_content {

        //上传图像样式
        .avatar-uploader .avatar {
          width: 178px;
          height: 178px;
          display: block;
        }
      }
    }

    //首页管理
    .home_wapped {
      display: grid;
      grid-template-rows: 1fr 1fr; //有几行 
      grid-template-columns: 1fr 1fr;

      .siwperWarpped {
        :deep(.el-upload) {
          width: 100%;
          height: 100%;
        }


        .swiper1 {
          margin: 5px;
          border: 1px dashed rgb(183, 173, 173);
          background: linear-gradient(135deg, #EAE3E3 0%, #D7FFFE 100%);

          .imgSize {
            width: 200px;
            height: 100px;
          }
        }
      }
    }

    .set {
      display: flex;
      flex-direction: column;

      .departmentSet {
        .el-tag.is-closable {

          margin-left: 10px;
        }

        .el-button--small {
          margin-left: 10px;
        }
      }

      .productSet {
        margin-top: 20px;

      }
    }
  }
}

//栏目内容样式

.demo-tabs> :deep(.el-tabs__content) {
  padding: 10px;
  font-size: 18px;

}

:deep(.el-upload-dragger) {
  padding: 0;
}
</style>
<!-- 上传图像样式 -->
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>